//
//  ALFilterView.m
//  ALUtils_Example
//
//  Created by mac on 2018/4/24.
//  Copyright © 2018年 anlun. All rights reserved.
//

#import "ALFilterView.h"
#import "Masonry.h"
#import "ALUtilsMacro.h"
#import "ALButton.h"
#import "ReactiveObjC.h"
#import "ALUtils.h"
#import "UIView+Frame.h"
#import "ADScreenAdaptation.h"
#import "ALUILabel.h"

static NSString *kFilterCellIdentify=@"kFilterCellIdentify";


static CGFloat leftTitHeight=50/2;
static CGFloat btnWidth=218/2;
static CGFloat btnHeight=60/2;
typedef NS_ENUM(NSInteger , FilterEnum) {
    FilterEnumClick,
    FilterEnumTxtClick
};
typedef void (^FilterCellBlock)(FilterEnum theEnum,id sender);
@interface ALFilterCell:UITableViewCell<UITextFieldDelegate>
@property (nonatomic , strong) UILabel *leftTitLbl;
@property (nonatomic , strong) ALFilterModel *filterModel;
@property (nonatomic , copy) FilterCellBlock cellBlock;
@property (nonatomic, strong) ALUILabel *lineLbl;
@end
@implementation ALFilterCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self.contentView addSubview:self.leftTitLbl];
        [self.leftTitLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(adsaW(24/2)));
            make.top.equalTo(self).offset(adsaH(20));
            make.right.equalTo(self).offset(-adsaW(24/2));
            make.height.equalTo(@(adsaH(15)));
        }];
        [self.contentView addSubview:self.lineLbl];
        [self.lineLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.equalTo(self);
            make.size.mas_equalTo(CGSizeMake(AL_ScreenWidth, adsaH(.5f)));
        }];
    }
    return self;
}
-(UILabel *)leftTitLbl{
    if (!_leftTitLbl) {
        _leftTitLbl =[[UILabel alloc] init];
        [_leftTitLbl setFont:[UIFont systemFontOfSize:30/2]];
        [_leftTitLbl setTextColor:AL_RGB(88,108,138)];
    }
    return _leftTitLbl;
}
-(void)setFilterModel:(ALFilterModel *)filterModel{
    
    [self.leftTitLbl setText:filterModel.optionName];
    [self.contentView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[ALButton class]]) {
            [obj removeFromSuperview];
        }
    }];
    
    [self.contentView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.tag>1000) {
            [obj removeFromSuperview];
        }
    }];
    
    if (filterModel.optionPattern==1) { //输入框
        UIView *inputView=[[UIView alloc] init];
        [inputView setBackgroundColor:AL_RGB(246,249,250)];
        [inputView setTag:1001];
        [self.contentView addSubview:inputView];
        [inputView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.leftTitLbl.mas_bottom).offset(adsaH(16));
            make.left.equalTo(self.contentView).offset(adsaW(24/2));
            make.right.equalTo(self.contentView).offset(-adsaW(24/2));
            make.height.height.mas_equalTo(adsaH(41));
        }];
        [inputView.layer setCornerRadius:2];
        [inputView.layer setBorderColor:[UIColor clearColor].CGColor];
        [inputView.layer setBorderWidth:.5f];
        [inputView.layer setMasksToBounds:YES];
        
        UITextField *mintxt=[[UITextField alloc] init];
        [mintxt setTag:1002];
        [mintxt setBackgroundColor:[UIColor whiteColor]];
        [mintxt setPlaceholder:@"最低"];
        [mintxt setReturnKeyType:UIReturnKeyDone];
        [mintxt setDelegate:self];
        [mintxt setText:filterModel.minTxtVal];
        [mintxt addTarget:self action:@selector(textFieldValueDidChange:) forControlEvents:UIControlEventEditingChanged];
//        [mintxt setKeyboardType:UIKeyboardTypeNumberPad];
        [mintxt setTextAlignment:NSTextAlignmentCenter];
        [inputView addSubview:mintxt];
        [mintxt mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(inputView).offset(adsaH(5.5));
            make.left.equalTo(inputView).offset(adsaW(12));
            make.size.mas_equalTo(CGSizeMake(adsaW(150), adsaH(30)));
        }];
        [mintxt setFont:[UIFont systemFontOfSize:13]];
        
        UITextField *maxtxt=[[UITextField alloc] init];
        [maxtxt setTag:1003];
        [maxtxt setBackgroundColor:[UIColor whiteColor]];
        [maxtxt setPlaceholder:@"最高"];
        [maxtxt setReturnKeyType:UIReturnKeyDone];
        [maxtxt setDelegate:self];
        [maxtxt setText:filterModel.maxTxtVal];
        [maxtxt addTarget:self action:@selector(textFieldValueDidChange:) forControlEvents:UIControlEventEditingChanged];
        [maxtxt setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
        [maxtxt setTextAlignment:NSTextAlignmentCenter];
        [inputView addSubview:maxtxt];
        [maxtxt mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(inputView).offset(adsaH(5.5));
            make.right.equalTo(inputView).offset(-adsaW(12));
            make.size.mas_equalTo(CGSizeMake(adsaW(150), adsaH(30)));
        }];
        [maxtxt setFont:[UIFont systemFontOfSize:13]];
        
        UILabel *lineLbl=[[UILabel alloc] init];
        [lineLbl setTag:1004];
        [lineLbl setBackgroundColor:AL_RGB(148,161,180)];
        [inputView addSubview:lineLbl];
        [lineLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(adsaW(26/2), adsaH(4/2)));
            make.center.equalTo(inputView);
        }];
        
        [[mintxt rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
//            if (x&&x.length>0) {
                filterModel.minTxtVal=x;
//            }
        }];
        [[maxtxt rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
//            if (x&&x.length>0) {
                filterModel.maxTxtVal=x;
//            }
        }];
        
        return;
    }
    
    [filterModel.options enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        __block ALFilterMinModel *minModel=obj;
        ALButton *btn=[ALButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundColor:[UIColor grayColor]];
        [btn setTitle:minModel.name forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:26/2]];
        [btn.titleLabel setLineBreakMode:NSLineBreakByTruncatingTail];
        [btn setTheBtnClickBlock:^(id sender) {
            if (filterModel.optionType == 0) { //单选
                BOOL isCheck=minModel.isCheck;
                [filterModel.options enumerateObjectsUsingBlock:^(ALFilterMinModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                    if (isCheck&&obj.value==0) { //默认选 不限了
//                        obj.isCheck=YES;
//                    }else{
                        obj.isCheck=NO;
//                    }
                }];
                minModel.isCheck=!isCheck;
            }else{ //多选
                minModel.isCheck=!minModel.isCheck;
            }
            if (self.cellBlock) {
                self.cellBlock(FilterEnumClick, nil);
            }
        }];
        [self.contentView addSubview:btn]; 
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.leftTitLbl.mas_bottom).offset(adsaH(16)+adsaH((10+btnHeight)*(idx/3)));
            make.left.equalTo(self.mas_left).offset(adsaW(24/2+(16/2+btnWidth)*(idx%3)));
            make.size.mas_equalTo(CGSizeMake(adsaW(btnWidth), adsaH(btnHeight)));
        }];
        
        if (minModel.isCheck) { //选中状态
            [btn setImage:[UIImage imageNamed:@"选中小"] forState:UIControlStateNormal];
            [btn setTitleColor:AL_RGB(36,129,215) forState:UIControlStateNormal];
            [btn setBackgroundColor:AL_RGB(244,250,255)];
            btn.layer.borderWidth=.5f;
            btn.layer.borderColor=AL_RGB(45,155,243).CGColor;
//            [btn setImage:[UIImage imageNamed:@"多选关闭"] forState:UIControlStateNormal];
//            [btn setImageEdgeInsets:UIEdgeInsetsMake(btnHeight-adsaH(30/2), btnWidth-adsaW(30/2), 0, 0)];
        }else{
            [btn setImage:nil forState:UIControlStateNormal];
            [btn setTitleColor:AL_RGB(132, 147, 167) forState:UIControlStateNormal];
            [btn setBackgroundColor:AL_RGB(246,249,250)];
            btn.layer.borderWidth=.0f;
            btn.layer.borderColor=[UIColor clearColor].CGColor;
//            [btn setImage:nil forState:UIControlStateNormal];
        }
        btn.layer.cornerRadius=1;
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, adsaW(4), 0, 0)];
    }];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (string&&!([ALUtils filterStr:string].length>0)) { //用于减
        return YES;
    }
    
    if ([string containsString:@"-"]) {
        return NO;
    }else if([@"0123456789" containsString:string]){
        return YES;
    }else{
        return NO;
    }
}
-(void)textFieldValueDidChange:(UITextField *)textField{
    NSLog(@"val=%@",textField.text);
    NSString *valStr=textField.text;
    if ([valStr containsString:@"-"]) {
        textField.text = [valStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [textField setNeedsDisplay];
    if (self.cellBlock) {
        self.cellBlock(FilterEnumTxtClick,textField);
    }
    return YES;
}
-(ALUILabel *)lineLbl{
    if (!_lineLbl) {
        _lineLbl=[[ALUILabel alloc] initLine];
    }
    return _lineLbl;
}
@end

static CGFloat bottomViewHeight=64;
@interface ALFilterView()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic , strong) ALUILabel *tableViewTopLine;
@property (nonatomic , strong) UITableView *theTableView;
@property (nonatomic , strong) UIView *bottomView;
@property (nonatomic , strong) ALButton *resetBtn;
@property (nonatomic , strong) ALButton *okBtn;
@property (nonatomic , assign) CGRect curTxtFrame; //当前操作textfield的frame
@property (nonatomic , strong) UIButton *tableFooterBtn;
@property (nonatomic, assign) BOOL isReset; //是否重置状态，默认YES
@end

@implementation ALFilterView

-(instancetype)init{
    self=[super init];
    if (self) {
        self.isReset=YES; //默认重置状态
        if (kSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"11.0")) {
            self.theTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else{
//            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        
        [self setBackgroundColor:[UIColor whiteColor]];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardDidShowNotification object:nil];
        [self p_initData];
        [self p_initView];
        
        NSString *str=@"筛选要求越严格，可能导致订单越少哦";
        UIButton *footerBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        [footerBtn setHeight:adsaH(118/2)];
        [footerBtn setTop:0];
        [footerBtn setLeft:adsaW(24/2)];
        [footerBtn setBackgroundColor:[UIColor clearColor]];
        [footerBtn setTitle:str forState:UIControlStateNormal];
        [footerBtn setTitleColor:RGB(148,161,180) forState:UIControlStateNormal];
        footerBtn.titleLabel.font=[UIFont systemFontOfSize:26/2];
        [footerBtn setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
        [footerBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        
        self.theTableView.tableFooterView=footerBtn;
    }
    return self;
}
- (void)p_initData{
    
}
- (void)p_initView{
    WeakSelf
    [self addSubview:self.theTableView];
    [self.theTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self);
        make.bottom.equalTo(self).offset(-adsaH(bottomViewHeight));
//        make.size.mas_equalTo(CGSizeMake(AL_ScreenWidth, AL_ScreenHeight-AL_NavigationBarBotom-AL_NavigationBarHeight-AL_TabBarHeight-adsaH(bottomViewHeight)));
        
//        make.size.mas_equalTo(CGSizeMake(AL_ScreenWidth,250));

//        make.bottom.equalTo(self).offset(-adsaH(bottomViewHeight+50));
    }];
    [self.theTableView addSubview:self.tableViewTopLine];
    [self.tableViewTopLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self.theTableView);
        make.size.mas_equalTo(CGSizeMake(AL_ScreenWidth, adsaH(.5f)));
    }];

    [self addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.mas_equalTo(adsaH(bottomViewHeight));
    }];
    [self.bottomView addSubview:self.resetBtn];
    [self.bottomView addSubview:self.okBtn];

    [self.resetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bottomView).offset(adsaH(12));
        make.left.equalTo(self.bottomView).offset(adsaW(12));
        make.size.mas_equalTo(CGSizeMake(adsaW(109), adsaH(40)));
    }];

    [self.okBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.resetBtn);
        make.left.equalTo(self.resetBtn.mas_right).offset(adsaW(8));
        make.size.mas_equalTo(CGSizeMake(adsaW(234), adsaH(40)));
    }];

    [self.resetBtn setTheBtnClickBlock:^(id sender) {
        weakself.isReset=YES;
        [weakself.options enumerateObjectsUsingBlock:^(ALFilterModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.optionPattern==1) { //输入框
                obj.minTxtVal=nil;
                obj.maxTxtVal=nil;
            }else if (obj.optionPattern==0){ //选择
                [obj.options enumerateObjectsUsingBlock:^(ALFilterMinModel * _Nonnull obj1, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj1.name isEqualToString:@"不限"]) {
                        obj1.isCheck=YES;
                    }else{
                        obj1.isCheck=NO;
                    }
                }];
            }else{
            }
        }];
        [weakself.theTableView reloadData];
    }];

    [self.okBtn setTheBtnClickBlock:^(id sender) {
        weakself.isReset=NO;
        if (weakself.selBack) {
            weakself.selBack(weakself.options,weakself.isReset);
        }
    }];
}
#pragma mark - datasource delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.options.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ALFilterCell *cell=[tableView dequeueReusableCellWithIdentifier:kFilterCellIdentify];
    [cell setFilterModel:self.options[indexPath.row]];
    __weak typeof(cell)weakCell = cell;
    WeakSelf
    [cell setCellBlock:^(FilterEnum theEnum, id sender) {
        switch (theEnum) {
            case FilterEnumClick:{
                [tableView reloadData];
            }
                break;
            case FilterEnumTxtClick:{
                 __strong typeof(weakCell)strongCell = weakCell;
                UITextField *txt=(UITextField *)sender;
                CGRect rect=txt.frame;
                weakself.curTxtFrame= [strongCell convertRect:rect toView:tableView];
            }
                break;
            default:
                break;
        }
    }];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [self getCellHeight:self.options[indexPath.row]];
}
-(CGFloat)getCellHeight:(ALFilterModel *)filterModel{
    NSInteger totalRow=filterModel.options.count/3+((filterModel.options.count%3>0)?1:0);
    CGFloat rowHeight=adsaH(10+btnHeight);
    if (filterModel.optionPattern==1) {
        return rowHeight+adsaH(20*2+leftTitHeight);
    }
    return totalRow*rowHeight+adsaH(20*2+leftTitHeight);
}
- (void)keyboardFrameChange:(NSNotification *)note
{
    NSDictionary *userInfo = note.userInfo;
    CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat offset = self.curTxtFrame.origin.y + self.curTxtFrame.size.height + 12/2*2+78/2 - keyboardFrame.origin.y;
    if (offset > 0) {
        [self.theTableView setContentOffset:CGPointMake(0, offset) animated:YES];
    }else{
        [self.theTableView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}
#pragma mark - get set
-(UITableView *)theTableView{
    if (!_theTableView) {
        _theTableView=[[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [_theTableView setDataSource:self];
        [_theTableView setDelegate:self];
        [_theTableView registerClass:[ALFilterCell class] forCellReuseIdentifier:kFilterCellIdentify];
        _theTableView.estimatedRowHeight = 150;
        [_theTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    }
    return _theTableView;
}
-(ALUILabel *)tableViewTopLine{
    if (!_tableViewTopLine) {
        _tableViewTopLine=[[ALUILabel alloc] initLine];
    }
    return _tableViewTopLine;
}
-(void)setOptions:(NSArray<ALFilterModel *> *)options{
    if (_options!=options) {
        _options=options;
    }
}
-(UIView *)bottomView{
    if (!_bottomView) {
        _bottomView=[[UIView alloc] init];
        [_bottomView setBackgroundColor:[UIColor whiteColor]];
        _bottomView.layer.shadowOffset = CGSizeMake(0, -1);
        _bottomView.layer.shadowOpacity = 0.2;
        _bottomView.layer.shadowColor = [UIColor blackColor].CGColor;
    }
    return _bottomView;
}

-(ALButton *)resetBtn{
    if (!_resetBtn) {
        _resetBtn=[ALButton buttonWithType:UIButtonTypeCustom];
        [_resetBtn setTitle:@"重置" forState:UIControlStateNormal];
        [_resetBtn.titleLabel setFont:[UIFont systemFontOfSize:30/2]];
        [_resetBtn setTitleColor:AL_RGB(132,147,167) forState:UIControlStateNormal];
        [_resetBtn setBackgroundColor:AL_RGB(237,243,248)];
        [_resetBtn.layer setCornerRadius:2];
        [_resetBtn.layer setBorderColor:[UIColor clearColor].CGColor];
        [_resetBtn.layer setBorderWidth:.5f];
        [_resetBtn.layer setMasksToBounds:YES];
    }
    return _resetBtn;
}
-(ALButton *)okBtn{
    if (!_okBtn) {
        _okBtn=[ALButton buttonWithType:UIButtonTypeCustom];
        [_okBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_okBtn setBackgroundColor:AL_RGB(45,155,243)];
        [_okBtn.titleLabel setFont:[UIFont systemFontOfSize:30/2]];
        [_okBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_okBtn.layer setBorderColor:[UIColor clearColor].CGColor];
        [_okBtn.layer setBorderWidth:.5f];
        [_okBtn.layer setMasksToBounds:YES];
    }
    return _okBtn;
}
@end
